import scrapy
import requests,json
from bid.items import BidItem
from bid.tools import *


class HeilongjiangSpider(scrapy.Spider):
    name = 'heilongjiang'
    allowed_domains = ['www.hljggzyjyw.org.cn/']
    start_urls = ['http://www.hljggzyjyw.org.cn/']
    url = 'http://www.hljggzyjyw.org.cn/EpointWebBuilder/rest/frontAppNotNeedLoginAction/getPageInfoList'
    t_dic ={
        '003002001001':['工程建设信息-招标/资审公告','1'],
        '003002001002':['工程建设信息-中标候选人公示','2'],
        '003002001003':['工程建设信息-中标结果公示','3'],
        '003002001004':['工程建设信息-项目澄清','2'],
        '003002001005':['工程建设信息-废标/流标公示','2'],
        '003002001006':['工程建设信息-评标结果','2'],
        '003002001007':['工程建设信息-合同公示','3'],
        '003002002001':['政府采购信息-采购/预审公告','1'],
        '003002002002':['政府采购信息-变更公告','2'],
        '003002002003':['政府采购信息-采购合同公示','2'],
        '003002002004':['政府采购信息-中标结果公示','3'],
    }
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36'}
    msg =[]
    def start_requests(self):
        for page in range(1,999999):
            data = {
                'params': '{"siteGuid":"7eb5f7f1-9041-43ad-8e13-8fcb82ea831a","categoryNum":"003002","pageIndex":"%s","controlname":"subpagelist"}'%page
            }
            res = requests.post(url=self.url,data=data,headers=self.headers).json()
            ls = res['custom']['infodata']
            if not ls:
                break
            for l in ls:
                item = {}
                item['link'] = 'http://www.hljggzyjyw.org.cn' + l['infourl']
                key = item['link'].split('/')[-3]
                if key not in self.t_dic:
                    continue
                item['title'] = l['title']
                item['time'] = l['infodate']
                item['classification'] = '黑龙江-'+self.t_dic[key][0]
                item['typ']=self.t_dic[key][-1]
                if redis_dupefilter(item) or item['time'].startswith('2021'):
                    self.msg.append(page)
                    break
                yield scrapy.Request(url=item['link'], callback=self.parse, meta={'item': item})
            if page in self.msg:
                print('完成')
                break
            time.sleep(len(ls))

    def parse(self, response):
        item = BidItem()
        item.update(response.meta['item'])
        item['content'] = get_content(response.text, '//div[@class="ewb-art-bd"]')
        item = get_field(dict(item))
        yield item